package cn.bytengine.stem.cluster.netty;

import cn.bytengine.stem.contexts.Context;

public class NettyClusterHostServer implements ClusterHostServer {
    private final NettyServer<?, ?> tcpServer;
    private final NettyServer<?, ?> udpMulticastServer;

    private boolean isTcpServerStartup = false;
    private boolean isUdpMulticastServerStartup = false;

    public NettyClusterHostServer(NettyServer<?, ?> tcpServer,
                                  NettyServer<?, ?> udpMulticastServer) {
        this.tcpServer = tcpServer;
        this.udpMulticastServer = udpMulticastServer;
    }

    // region implemented methods
    @Override
    public void startup(Context context) throws Exception {
        try {
            tcpServer.startup(context);
            isTcpServerStartup = true;
            udpMulticastServer.startup(context);
            isUdpMulticastServerStartup = true;
        } catch (Exception e) {
            shutdown();
            throw e;
        }
    }

    @Override
    public void shutdown() {
        if (isTcpServerStartup) {
            tcpServer.shutdown();
            isTcpServerStartup = false;
        }
        if (isUdpMulticastServerStartup) {
            udpMulticastServer.shutdown();
            isUdpMulticastServerStartup = false;
        }
    }

    // endregion
}
